package com.cy.pet.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cy.pet.common.mapper.UserMapper;
import com.cy.pet.common.pojo.User;
import com.cy.pet.common.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description:
 * @author: LiuXingYu
 * @date: 2021/9/30 17:02
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    public String login(User user) {
        return null;
    }
    @Transactional
    @Override
    public Boolean register(User user) {
        //将密码进行PasswordEncoder加密
        String password = user.getPassword();
        String encodePassword = passwordEncoder.encode(password);
        //根据用户名查询数据库的条件选择器
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",user.getUsername());
        //查询数据库是否有此用户名的记录
        User user1 = userMapper.selectOne(userQueryWrapper);
        if(user1 != null) return false;
        user.setPassword(encodePassword);
        //插入用户记录
        int flag = userMapper.insert(user);
        if(flag == 0) return false;
        return true;
    }

    @Override
    public User getUserByUserName(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }
}
